// #ifdef H5
import wx from 'jweixin-module';
import config from '@/config'

export default {
	// 判断微信环境
	isWechat() {
		const ua = navigator.userAgent.toLowerCase();
		return ua.includes('micromessenger');
	},

	// 初始化配置
	initWxShare(shareConfig = {
		type,
		title,
		desc,
		imgUrl,
		link
	}) {
		let appId = 'wx084fc0165fb7a025'
		uni.request({
			url: config.baseUrl + '/wxApi/getSignature', // 替换为后端签名接口
			method: 'get',
			data: {
				url: window.location.href.split('#')[0]
			},
			success: (res) => {
				const {
					timestamp,
					nonceStr,
					signature
				} = res.data;
				wx.config({
					debug: true, // 生产环境关闭
					appId,
					timestamp,
					nonceStr,
					signature,
					jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
				});

				wx.ready(() => {
					if (type === '微信') {
						// 分享给好友
						wx.updateAppMessageShareData({
							title: shareConfig.title,
							desc: shareConfig.desc,
							imgUrl: shareConfig.imgUrl,
							link: shareConfig.link
						});
					}
					if (type === '朋友圈') {
						// 分享到朋友圈
						wx.updateTimelineShareData({
							title: shareConfig.title,
							imgUrl: shareConfig.imgUrl,
							link: shareConfig.link,
						});
					}
				});

				wx.error((err) => {
					console.error('微信配置失败:', err);
				});
			}
		});
	}
};
// #endif